package com.modudf.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.modudf.common.XML2BeanUtils;
import com.modudf.domain.ResultInfo;
import com.modudf.domain.User;
import com.modudf.exception.ConnectiontException;
import com.modudf.exception.XMLConvertException;
import com.modudf.service.LoginUserManager;
import com.modudf.service.LoginUserManagerImpl;

public class LoginUserServlet extends HttpServlet {

	private static final long serialVersionUID = -5115544300322884843L;

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) {
		String url = request.getParameter("url");
		String userName = request.getParameter("userName");
		String userPwd = request.getParameter("userPwd");
		LoginUserManager manager = new LoginUserManagerImpl();
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/xml;charset=UTF-8");
		ResultInfo result;
		try {
			User user = manager.loginUser(new User(url, userName, userPwd));
			if (user != null) {
				result = new ResultInfo();
				result.setData(user);
			} else {
				result = new ResultInfo(-1, "无法连接到数据库");
			}
		} catch (ConnectiontException e) {
			e.printStackTrace();
			result = new ResultInfo(-1, e.getMessage());
		}
		try {
			PrintWriter out = response.getWriter();
			out.println(XML2BeanUtils.bean2XmlString(result));
			out.close();
		} catch (XMLConvertException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
